<?php

namespace app\admin\controller;

use app\admin\model\PurchaseProduct;
use app\admin\model\PurchaseCar;
use app\common\BaseHelper as Helper;
use think\Db;
use think\Exception;
use think\Request;

class Purchase extends Base
{

    public function index(){
        $sup = \app\admin\model\Supplier::where('status',1)->select();

        $request = $this->request;
        $param = $request->param();
        // Reset filter
        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }
        if($request->isAjax()){
            $model = model($this->model);
            // 每页起始条数
            $start = ($param['page'] - 1) * $param['limit'];
            // 每页显示条数
            $length = $param['limit'] + 1;
            // 排序条件
            $order = 'create_date DESC';
            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                $where = array_merge($this->defaultWhere, $where);
            }
            $data = $model->where($where)->limit($start, $length)->order($order)->select();
            $count = $model->where($where)->count();
            if($data){
                // 处理列表数据
                foreach ($data as &$v){
                    $SupplierName = \app\admin\model\Supplier::getSupplierName($v['supplier_id']);
                    $v['SupplierName'] = $SupplierName;
                    $UserName = \app\admin\model\Admin::getUserName($v['create_user']);
                    $v['UserName'] = $UserName;
                    $total_num = 0;
                    $total_price = 0;
                    $PurchaseProduct = PurchaseProduct::where('purchase_id',$v['id'])->select();
                    foreach ($PurchaseProduct as $val){
                        $total_num += $val['pu_stock'];
                        $total_price += $val['total_price'];
                    }
                    $v['total_num'] = $total_num;
                    $v['total_price'] = sprintf("%.2f",$total_price/100);
                }
            }
            $result = [
                'code' => '0',
                'msg' => '',
                'data' => $data,
                'count' => $count,
            ];
            return json($result);
        }

        return $this->fetch($this->indexView,[
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param(),
            'sup' => $sup
        ]);
    }

    /**
     * Add
     */
    public function add(Request $request){
        $param = $request->param();
        if(isset($param['supid'])){
            $Supplier = \app\admin\model\Supplier::get($param['supid']);
            if($Supplier){
                $this->assign('supname',$Supplier->name);
                $supinfo = ['supid'=>$param['supid'],'supname'=>$Supplier->name];
                session('SUPINFO',$supinfo);
            }else{
                return $this->error('请选择供应商','/admin/purchase/index');
            }
        }else{
            return $this->error('请选择供应商','/admin/purchase/index');
        }

        if(isset($param['supid'])){
            $this->assign('supid',$param['supid']);
        }else{
            $this->assign('supid','');
        }
        return $this->fetch();
    }

    /**
     * Add Post
     */
    public function addPost(Request $request, $redirect = ''){
        return parent::addPost($request, '');
    }

    /**
     * Edit
     */
    public function edit(Request $request){
        return parent::edit($request);
    }

    /**
     * Edit Post
     */
    public function editPost(Request $request, $redirect = ''){
        return parent::editPost($request, '');
    }

    //获取供应商下的商品
    public function get_supproduct(Request $request){
        $param = $request->param();
        if(empty($param['supid'])){
            return $this->error('缺少参数');
        }
        if($request->isAjax()){
            // 每页起始条数
            $start = ($param['page'] - 1) * $param['limit'];
            // 每页显示条数
            $length = $param['limit'];
            $join = [
                ['__STOCK__ s','s.product_id=a.id'],
                ['__PRODUCT_CATEGORY__ c','c.id=a.category_id']
            ];

            $where = [
                'a.supplier_id' => $param['supid'],
                'a.status' => 1
            ];
            if(isset($param['name']) && $param['name']){
                $where['a.name'] = ['like', '%'.$param['name'].'%'];
            }
            $field = 'a.id,a.name,a.bar_code,a.unit,a.supplier_id,a.img_url,a.spec,a.purchase_price,s.marketable,c.name as cname';
            $info = db('product')->alias('a')->where($where)->join($join)->field($field)->limit($start, $length)->select();
            $count = db('product')->alias('a')->where($where)->join($join)->field($field)->count();
            $result = [
                'code' => '0',
                'msg' => '',
                'data' => $info,
                'count' => $count,
            ];
            return json($result);
        }else{
            return $this->view->fetch('purchase/select_product', [
                'pageSize' => ['url' => fullUrl($request->path())],
                'searchFields' => $this->searchFields,
                'param' => $request->param()
            ]);
        }
    }

    public function select_product(Request $request){
        $param = $request->param();
        $this->assign('supid',$param['supid']);
        return $this->fetch();
    }

    public function save_caigou_session(Request $request){
        $param = $request->param();
        $sessioncaigouId = session('caigouId');
        $supinfo = session('SUPINFO');
        if($param){
            $data = json_decode($param['data'],true);
            $res = PurchaseCar::where(['purchase_id'=>$sessioncaigouId,'supid'=>$supinfo['supid']])->select();
            if($res){
                //采购车已经存在
                $edit = [];
                $add = [];
                foreach ($data as $v){
                    $flag = true;
                    foreach ($res as $val){
                        if($v['id'] == $val['product_id']){
                            array_push($edit,$val['product_id']);
                            $flag = false;
                            break;
                        }
                    }
                    if($flag){
                        array_push($add,[
                            'purchase_id' => $sessioncaigouId,
                            'product_id' => $v['id'],
                            'caigou_num' => $v['caigou_num'],
                            'supid' => $v['supid'],
                            'name' => $v['name'],
                            'purchase_price' => $v['purchase_price'],
                            'bar_code' => $v['bar_code'],
                            'store_count' => $v['store_count'],
                            'unit' => $v['unit'],
                            'spec' => $v['spec']
                        ]);
                    }
                }
                if($edit){
                    PurchaseCar::where(['purchase_id'=>$sessioncaigouId])->where('product_id','in',$edit)->setInc('caigou_num');
                }
                if($add){
                    $PurchaseCar = new PurchaseCar();
                    $PurchaseCar->saveAll($add,false);
                }
                $result = [
                    'code' => '1',
                    'msg' => '',
                    'data' => '',
                ];
                return json($result);
            }else{
                //采购车不存在
                $caigouId = Helper::getUUID();
                $dataarr = [];
                foreach ($data as $v){
                    array_push($dataarr,[
                        'purchase_id'=>$caigouId,
                        'product_id'=>$v['id'],
                        'caigou_num' => $v['caigou_num'],
                        'supid' => $v['supid'],
                        'name' => $v['name'],
                        'purchase_price' => $v['purchase_price'],
                        'bar_code' => $v['bar_code'],
                        'store_count' => $v['store_count'],
                        'unit' => $v['unit'],
                        'spec' => $v['spec']
                    ]);
                }
                $PurchaseCar = new PurchaseCar();
                if($PurchaseCar->saveAll($dataarr,false)){
                    $result = [
                        'code' => '1',
                        'msg' => '',
                        'data' => $caigouId,
                    ];
                    session('caigouId',$caigouId);
                    return json($result);
                }
            }
        }else{

        }
    }

    public function get_session_pro(){
        $caigouid = session('caigouId');
        $supinfo = session('SUPINFO');
        $join = [
            ['__PRODUCT__ p','p.id=a.product_id']
        ];
        $field = 'a.*,p.img_url';
        $res = db('purchase_car')->alias('a')->join($join)->where(['a.purchase_id'=>$caigouid,'a.supid'=>$supinfo['supid']])->field($field)->select();
        $allprice = 0;
        foreach ($res as &$v){
            $allprice += $v['purchase_price'] * $v['caigou_num'];
            $v['purchase_price'] = sprintf("%.2f",$v['purchase_price']/100);
        }
        $result = [
            'code' => '0',
            'msg' => '',
            'data' => $res,
            'allprice' => sprintf("%.2f",$allprice/100)
        ];
        return json($result);
    }

    public function edit_purchase_car(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id']) || empty($param['product_id']) || !preg_match("/^[1-9][0-9]*$/",$param['value'])){
                return $this->error('参数非法');
            }
            Db::startTrans();
            try{
                $PurchaseCar = PurchaseCar::get($param['id']);
                if($PurchaseCar){
                    $Product = \app\admin\model\Product::where('id',$param['product_id'])->lock(true)->find();
                    if($Product){
                        if($param['field'] == 'caigou_num'){
                            $PurchaseCar->caigou_num = $param['value'];
                        }else{
                            $PurchaseCar->purchase_price = $param['value'] * 100;
                        }
                        $PurchaseCar->save();
                        Db::commit();
                        return $this->success('ok');
                    }else{
                        return $this->error('商品信息异常');
                    }
                }else{
                    return $this->error('数据异常');
                }
            }catch (Exception $ex){
                Db::rollback();
                return $this->error($ex->getMessage());
            }
        }else{
            return $this->error('非法请求');
        }
    }

    public function save_purchase(Request $request){
        if($request->isPost()){
            $createuserid = session('ADMIN')['id'];
            $param = json_decode($request->param()['data'],true);
            if(count($param) > 0){
                Db::startTrans();
                try{
                    $HeadPurchase = new \app\admin\model\Purchase();
                    $HeadPurchase->id = $param[0]['purchase_id'];
                    $HeadPurchase->supplier_id = $param[0]['supid'];
                    $HeadPurchase->create_user = $createuserid;
                    if(!empty($request->param()['remarks'])){
                        $HeadPurchase->remarks = $request->param()['remarks'];
                    }
                    $HeadPurchase->save();
                    $array = [];

                    foreach ($param as $v){
                        if($v['caigou_num'] < 1){
                            return $this->error('请求数据异常');
                        }
                        $id = Helper::getUUID();
                        array_push($array,[
                            'id'=>$id,
                            'purchase_id' => $param[0]['purchase_id'],
                            'product_id' => $v['product_id'],
                            'product_name' => $v['name'],
                            'bar_code' => $v['bar_code'],
                            'spec' => $v['spec'],
                            'pu_stock' => $v['caigou_num'],
                            'unit' => $v['unit'],
                            'purchase_price' => $v['purchase_price'],
                            'total_price' => (int)$v['total_price']
                        ]);
                    }
                    if($array){
                        $prmodel = new PurchaseProduct();
                        $prmodel->saveAll($array,false);
                    }
                    //删除car
                    PurchaseCar::where('purchase_id',$param[0]['purchase_id'])->delete();
                    Db::commit();
                    //修改商品进价
                    $this->updatepurchase_price($param);
                    return $this->success('新增采购单成功','/admin/purchase/index');
                }catch (Exception $ex){
                    Db::rollback();
                    return $this->error($ex->getMessage());
                }
            }else{
                return $this->error('请求数据异常');
            }
        }else{
            return $this->error('非法请求');
        }
    }

    public function detail(){
        $param = $this->request->param();
        $model = model($this->model);
        $id = $param['id'];
        $fields = 'a.*,r.name,o.login_name';
        $info = $model
            ->alias('a')
            ->where('a.id',$id)
            ->join('supplier r','r.id=a.supplier_id')
            ->join('operator o','o.id=a.create_user')
            ->field($fields)
            ->find();
        $this->assign('info',$info);

        // Reset filter
        if ($this->request->param('reset')) {
            return redirect(fullUrl($this->request->path()));
        }
        if($this->request->isAjax()){
            $PurchaseProduct = PurchaseProduct::where('purchase_id',$id)->select();
            foreach ($PurchaseProduct as &$v){
                $v['unit'] = get_product_unit()[$v['unit']];
            }
            $result = [
                'code' => '0',
                'msg' => '请求成功',
                'data' => $PurchaseProduct
            ];
            return json($result);
        }

        return $this->fetch('detail', [
            'pageSize' => ['url' => fullUrl($this->request->path())],
            'searchFields' => $this->searchFields,
            'param' => $this->request->param()
        ]);
    }

    public function delete_purchase_car(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(!empty($param['id'])){
                db('purchase_car')->where('id',$param['id'])->delete();
                return $this->success('删除成功');
            }else{
                return $this->error('参数错误');
            }
        }else{
            return $this->error('非法请求');
        }
    }

    //修改商品进价
    private function updatepurchase_price($data){
        if(is_array($data)){
            $list = [];
            foreach ($data as $v){
                array_push($list,['id'=>$v['product_id'],'purchase_price'=>$v['purchase_price']]);
            }
            $model = new \app\admin\model\Product();
            $model->saveAll($list);
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if(isset($param['id']) && $param['id']){
            $where['id'] = ['like', '%'.$param['id'].'%'];
        }

        return $where;
    }
}